package com.skyit.bigevent.controller;

import com.skyit.bigevent.pojo.Result;
import com.skyit.bigevent.pojo.User;
import com.skyit.bigevent.service.UserService;
import com.skyit.bigevent.utils.JwtUtil;
import com.skyit.bigevent.utils.Md5Util;
import com.skyit.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        User u = userService.findByUsername(username);
        if (u==null){
            userService.add(username,password);
            return Result.success();
        }else {
            return Result.error("用户已存在");
        }
    }

    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        User byUsername = userService.findByUsername(username);
        if (byUsername==null){
            return Result.error("用户不存在");
        }
        if (Md5Util.getMD5String(password).equals(byUsername.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",byUsername.getId());
            claims.put("username",byUsername.getUsername());
            String token = JwtUtil.genToken(claims);
            //存储用户信息token存储到redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        Map<String,Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     * @return
     */
    @PutMapping("/update")
    public Result update11(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }
    /**
     * 更新用户头像
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    /**
     * 更新用户密码
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //获取用户信息,校验参数
        String oldPwd = params.get("oldPwd");
        String newPwd = params.get("newPwd");
        String rePwd = params.get("rePwd");
        //参数校验是否有空值
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("参数错误");
        }
        //校验旧密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        if (!Md5Util.getMD5String(oldPwd).equals(user.getPassword())){
            return Result.error("旧密码错误");
        }
        //校验新密码和确认密码是否一致
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        userService.updatePwd(newPwd);
        //删除redis中的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
